import React from 'react'
// ===================================================================== Temp
import TableModal from '#cpt/temp/TableModal'
import Controls from '#cpt/temp/Controls'
// ===================================================================== global declare
const { $fn, $Lazy } = window
// ===================================================================== Lazy
const Title = $Lazy.load(()=>import('#tp/title/title'))
const Button = $Lazy.load(()=>import('@antd/button'))
const Table = $Lazy.load(()=>import('@antd/table'))

// 删除
const del = (data, rows) => {
	data = $fn.copy(data)
	data.forEach( (v,i) => {
		if(v.uuid === rows.uuid ){ data[i] = null }
	})
	
	return data.filter( v=> v!==null)
}
// 删除判断 selectedKeys
const getSelectedKeys = (selectData, selectedKeys) => {
	const stack = []
	selectedKeys.forEach( v =>{
		selectData.forEach( m =>{
			if(m.uuid === v){
				stack.push(v)
			}
		})
	})
	return Array.from(new Set(stack))
}
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		selectedKeys:[],
		selectedKeys2: [],
		selectData: [],
		price: '0.00',
		forms : [
			{ label: '物价名称',		name: 'item_name',	width:200 },
			{ label: '物价代码',		name: 'price_code',	width:200 },
		]
	}
	
	model = {}
	
	componentDidMount(){
		const { project_id } = $fn.getCenterQuery()
		this.query = { project_id }
	}
	
	// paging
	fetch = callback => $fn.fetch.call(this,'qt-item-source/chargeSelect', { paging:'get'}).then(data=>{
		callback?.()
	})
	
	// 打开弹窗并传递参数
	open = (rows, info) => {
		this.modal.open()
		const { data } = this.state
		
		if(!$fn.hasArray(data)){
			this.fetch(()=>{
				this.backShow(rows)
			})
		}else{
			this.backShow(rows)
			this.table.resize()
		}
		this.query.hosp_id = info?.case_info?.hosp_id
	}
	// 回显
	backShow = selectData => {
		if($fn.hasArray(selectData)){
			this.setState(()=>{
				let selectedKeys = selectData.map( (v,i) => {
					v.index = i
					return v.uuid
				})
				
				selectedKeys = Array.from(new Set(selectedKeys))
				
				return { selectedKeys, selectData, price: this.getPrice(selectData) }
			})
		}
	}
	
	// 表单
	cols = [
		{ title: '名称', 		dataIndex: 'item_name', width:'50%'},
		{ title: '物价代码', 	dataIndex: 'price_code'},
		{ title: '参考价', 		dataIndex: 'price' },
	]
	
	cols2 = [
		...this.cols,
		{ title: '操作', 		width:60, render: (text, { index }) => <Button label='删除' onClick={()=>{
			this.setState(({ selectData, selectedKeys }) => {
				selectData = $fn.copy(selectData)
				index = selectData.findIndex((v,i) => v.index === index )
				selectData.splice(index, 1)
				
				return { selectData, selectedKeys:getSelectedKeys(selectData, selectedKeys), price:this.getPrice(selectData) }
			})
		}} /> },
	]
	
	controls = ()=>{
		return [
			Controls.click.call(this,'删除', () => {
				
				this.setState( ({ selectData, selectedKeys2, selectedKeys }) => {
					selectData = $fn.copy(selectData)
					
					selectData.forEach( (v,i) =>{
						selectedKeys2.forEach( m => {
							if( +v.index === m ){
								selectData[i] = null
							}
						})
					})
					
					selectData = selectData.filter( v => v !== null)
					
					return { selectData, selectedKeys:getSelectedKeys(selectData, selectedKeys), price:this.getPrice(selectData)  }
				} )
				
				
			}, {disabled: !$fn.hasArray(this.state.selectedKeys2)})
		]
	}
	
	
	// 计算价格
	getPrice = selectData =>{
		const price = selectData.reduce((total,value) => total + +value.price, 0)
		return  price.toFixed(2)
	}
	
	render(){
		const { selectData, selectedKeys2, price } = this.state
		return (
			<>
				{
					TableModal.call(this,{ title: '收费选择', width:'60%', height:'99%', noRefresh:true,
						bodyStyle:{padding:'0 10px 0'},
						hasOkDisabled:false,
						table:{ 
							simple:true,
							selectData: selectData,
							checkedNoChange:true,
							onSelectAll: (selectedRows, selected) => {
								selectedRows.forEach((v,i)=>{
									v.index = i
								})
								this.setState({ selectData: selectedRows, price:this.getPrice(selectedRows) })
								
							},
							onSelect: (selectedKeys, selectedRows) => {
								this.setState({ selectedKeys, selectedKeys2:[] })
							},
							onRow: (rows, selected) => {
								const onSelect = () => {
									this.setState(({ selectData }) => {
										selectData = [ ...$fn.copy(selectData), rows ]
										selectData.forEach((v,i) => {
											v.index = i
										})
										return { selectData, price:this.getPrice(selectData) }
									})
								}
								if(typeof selected === 'boolean'){
									if(selected){
										onSelect()
									}else{
										this.setState(({ selectData }) => {
											selectData = del(selectData, rows)
											return { selectData, price:this.getPrice(selectData)  }
										})
									}
								}else{
									onSelect()
								}
							}
						},
						prefix: <Title title='物价列表' />,
						close: ()=> {
							this.setState({ selectData:[],  selectedKeys2: [], price: '0.00' })		// 弹窗关闭，重置物价总价  2021-8-12 --马婷
						},
						suffix: (
							<>
								<Title title='已选物价' className='mb10' controls={this.controls()} />
								<Table 
									type			= 'checkbox'
									data 			= { selectData }
									cols 			= { this.cols2}
									wrapClassName 	= 'mlr'
									selectedKeys	= { selectedKeys2 }
									isIndex
									simple
									onSelect		= { selectedKeys => this.setState({ selectedKeys2: selectedKeys })}
								/>
								<dl className='fxm h30 f14 tc tbor1'>
									<dt className='ex rbor1'>总计</dt>
									<dd className='ex b' style={{color:'red'}}>{price}</dd>
								</dl>
							</>
						),
						onOk : ()=> {
							this.modal.close()
							this.props?.onSelect(price, selectData)
						}
					})
				}
			</>
		)
	}
}

export default Index